package com.ericsson.resourceplanner.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import com.ericsson.resourceplanner.dao.UserDao;
import com.ericsson.resourceplanner.dao.entity.Employee;
import com.ericsson.resourceplanner.dao.entity.EmployeeRole;

@Repository
public class UserDaoImpl implements UserDao{

	@Autowired
	private EntityManagerFactory entityManagerFactory;

	@Override
	public Employee findByUserName(String username) {
		// TODO Auto-generated method stub
		// ApplicationContext ctx= new ClassPathXmlApplicationContext("servlet-context.xml");		
		//EntityManagerFactory entityManagerFactory = (EntityManagerFactory) ctx.getBean("entityManagerFactory");
		EntityManager em = entityManagerFactory.createEntityManager();
		Query query=em.createNamedQuery("fetchEmployee");
		query.setParameter("signum", username);
		Employee emp=(Employee) query.getSingleResult();
		return emp;
	}

	public static void main(String[] args) {
		ApplicationContext ctx= new ClassPathXmlApplicationContext("servlet-context.xml");

		EntityManagerFactory factory = (EntityManagerFactory) ctx.getBean("entityManagerFactory");
		EntityManager em = factory.createEntityManager();
		System.out.println("lme"+ em);

		//		Query query=em.createNamedQuery("select * from employee");
		//		List lst=query.getResultList();
		UserDaoImpl userDaoImpl =  ctx.getBean("userDaoImpl",UserDaoImpl.class);
		List<EmployeeRole> empRoles=userDaoImpl.findByUserName("ECHOAVI").getEmployeeRoles();
		for(EmployeeRole er:empRoles){
			System.out.println("The role is"+er.getRole().getRoleName());
		}

	}

	@Override
	public int updateUserWithResettedPassword(String userSignum, String pass) {
		
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		int updateCount=0;
		if(entityManager!=null)
		{
			EntityTransaction updateTransaction = entityManager.getTransaction();
			updateTransaction.begin();
			Employee emp = findByUserName(userSignum);
			Query query = entityManager.createQuery("update Employee e SET e.password= :pass " + "WHERE e.signumId= :username");	
			query.setParameter("pass", pass);
			query.setParameter("username", userSignum);
			updateCount = query.executeUpdate();
			System.out.println("Update count:"+updateCount);
			if (updateCount > 0) {
				System.out.println("Done...");	
			}	
			updateTransaction.commit();
		}
		return updateCount;
	}





}
